package com.tin.controller;

import com.alibaba.fastjson.JSONObject;
import com.tin.bean.Audience;
import com.tin.bean.Msg;
import com.tin.bean.TokenInfo;
import com.tin.bean.User;
import com.tin.exception.ServiceRuntimeException;
import com.tin.service.UserService;
import com.tin.util.DateUtil;
import com.tin.util.JwtUtil;
import com.tin.util.MD5;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.sound.midi.Soundbank;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserContoller {

    @Autowired
    private Audience audience;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenInfo tokenInfo;

    @GetMapping("/test")
    @ResponseBody
    public Msg test(HttpServletRequest request) {
        System.out.println(request.getHeader("authorization"));
        return Msg.sucess();
    }

    @ApiOperation(value = "登录", notes = "请求参数为username和password")
    @PostMapping("/user/login")
    @ResponseBody
    public Msg login(@RequestParam String username, @RequestParam String password) throws ParseException {

        //登录时首先判断用户在数据库中是否存在
        User user = userService.findUserByUsernameameAndPassword(username, MD5.encrypByMd5(password));
        if (user == null)
            throw new ServiceRuntimeException("1004", "用户名或密码错误");

        Map<String, Object> map = new HashMap<>();

        //判断用户是否已经登录，未登录则获得token返回并存入redis；如果已经登录则更新token过期时间
        String jwtToken = JwtUtil.createJWT(username, user.getId(), audience.getClientId(),
                audience.getName(), 24 * 3600 * 1000, audience.getBase64Secret());
        jwtToken = "bearer;" + jwtToken;
        map.put("token", jwtToken);
        map.put("currentUser", username);

        //重复登录时，在数据库中删除原有的token
        List<TokenInfo> list = userService.findTokenByUsername(username);
        if (list.size()>0)
            userService.deleteTokenByUsername(username);


        //登录成功，将token放入数据库保存，用于延期、注销
        tokenInfo.setUsername(username);
        tokenInfo.setIp("127.0.0.1");
        String token = jwtToken.substring(7);
        tokenInfo.setToken(token);
        tokenInfo.setExpireDate(DateUtil.format(new Date()));
        userService.addToken(tokenInfo);
        return Msg.sucess().setData(map);
    }

    @ApiOperation(value = "登出", notes = "url中指定需要登出的username")
    @DeleteMapping("/{username}/logout")
    @ResponseBody
    public Msg logout(@PathVariable String username) {
        //根据用户名清除redis中的token

        return Msg.sucess();
    }

    @ApiOperation(value = "添加用户", notes = "json格式，key为username、password、mail、createDate、role")
    @PostMapping("/user/add")
    @ResponseBody
    public Msg addUser(@RequestBody JSONObject jsonParam) throws Exception {
        String username = jsonParam.getString("username");
        if (username.equals("admin"))
            return Msg.fail().setMsg("admin为管理员，不能注册");
        String password = jsonParam.getString("password");
        String mail = jsonParam.getString("mail");
        String createDate = jsonParam.getString("createDate");
        Integer role = jsonParam.getInteger("role");

        //如果请求时没传入createDate，则为当前时间
        if (createDate == null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            createDate = sdf.format(new Date());
        }

        if (role == null)
            role = 100;

        //判断用户是否已经存在
        if (userService.findUserByUsername(username) != null) {
            return new Msg("400", "用户名重复");
        }
        //如果不存在，则添加该用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(MD5.encrypByMd5(password));
        user.setMail(mail);
        user.setCreatDate(createDate);
        user.setRole(role);

        Integer id = userService.addUser(user);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", id);
        return Msg.sucess().setData(map);
    }

    @ApiOperation(value = "删除用户", notes = "json格式，key为username，多个使用逗号分隔")
    @PostMapping("/user/delete")
    @ResponseBody
    public Msg deleteUser(@RequestBody JSONObject jsonParam) {
        String username = jsonParam.getString("username");
        if (username.contains("admin"))
            return Msg.fail().setMsg("不允许删除admin");
        List<User> list = new ArrayList<>();
        if (username.contains(",")) {
            String[] users = username.split(",");
            for (String s : users) {
                User user = new User(s);
                list.add(user);
            }
        } else {
            User user = new User(username);
            list.add(user);
        }
        userService.deleteUser(list);
        return Msg.sucess();
    }


    //通过request对象获得输入流，解析json
    public JSONObject getJSONParam(HttpServletRequest request) {
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }


}
